﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Services;

namespace ZenSystemService.Api.Common.Auth
{
    public class TokenService
    {
        private readonly IConfiguration _configuration;

        public TokenService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public string GenerateToken(User user, IEnumerable<Claim> additionClaims = null)
        {
            var jwtSettings = _configuration.GetSection("JwtSettings");
            var secretKey = jwtSettings["SecretKey"];
            var issuer = jwtSettings["Issuer"];
            var audience = jwtSettings["Audience"];
            var expires = DateTime.Now.AddYears(int.Parse(jwtSettings["ExpiresInYears"]));

            var institutionId = "";
            if(user.InstitutionId != null) 
            {
                institutionId = user.InstitutionId.ToString();
            }
            
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(UserClaimTypes.InstitutionId, institutionId),
                new Claim(UserClaimTypes.UserId, user.UserId.ToString()),
            };
            if(additionClaims != null && additionClaims.Any())
                claims = claims.Union(additionClaims).ToArray();

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer,
                audience,
                claims,
                expires: expires,
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public string GenerateJwtToken(string clientId)
        {
            string secretKey = "";
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(secretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                new Claim(ClaimTypes.NameIdentifier, clientId) // 将客户端ID作为主体的一部分
            }),
                Expires = DateTime.UtcNow.AddHours(1), // 设置过期时间
                Issuer = "",
                Audience = "",
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token); // 返回生成的 JWT Token
        }

        
    }
}